package com.example.springboot.service.impl;

import com.example.springboot.page.Page;
import com.example.springboot.service.BaseSearchService;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 搜索服务基类实现
 * @Author wenlinyu
 * @Date: 2021/2/14 20:46
 * @Version 1.0
 */
@Service
public class BaseSearchServiceImpl<T> implements BaseSearchService<T> {

    private final Logger logger = LoggerFactory.getLogger(BaseSearchServiceImpl.class);

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    /**
     * 查询
     * @param keyword
     * @param clazz
     * @return
     */
    @Override
    public List<T> query(String keyword, Class<T> clazz) {
        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(new QueryStringQueryBuilder(keyword))
                .withSort(SortBuilders.scoreSort().order(SortOrder.DESC))
                // .withSort(new FieldSortBuilder("createTime").order(SortOrder.DESC))
                .build();
        return elasticsearchTemplate.queryForList(searchQuery, clazz);
    }

    /**
     * 高亮显示-查询
     * @param keyword
     * @param indexName
     * @param fieldNames
     * @return
     */
    @Override
    public List<Map<String, Object>> quertHit(String keyword, String indexName, String... fieldNames) {
        // 构造查询条件，使用标准分词器
        QueryBuilder matchQuery = createQueryBuilder(keyword, fieldNames);
        // 设置高亮，使用默认的highlighter高亮器
        HighlightBuilder highlightBuilder = createHighightBuilder(fieldNames);
        // 设置查询字段
        SearchResponse response = elasticsearchTemplate.getClient().prepareSearch(indexName)
                .setQuery(matchQuery)
                .highlighter(highlightBuilder)
                .setSize(10000) // 设置一次返回的文档数量，最大值：10000
                .get();
        // 返回搜索结果
        SearchHits hits = response.getHits();
        return getHitList(hits);
    }

    /**
     * 高亮显示-分页查询
     * @param pageNo
     * @param pageSize
     * @param keyword
     * @param indexName
     * @param fieldNames
     * @return
     */
    @Override
    public Page<Map<String, Object>> quertHitByPage(int pageNo, int pageSize, String keyword, String indexName,
                                                 String... fieldNames) {
        // 构造查询条件，使用标准分词器
        QueryBuilder matchQuery = createQueryBuilder(keyword, fieldNames);
        // 设置高亮，使用默认的highlighter高亮器
        HighlightBuilder highlightBuilder = createHighightBuilder(fieldNames);
        // 设置高亮字段
        SearchResponse response = elasticsearchTemplate.getClient().prepareSearch(indexName)
                .setQuery(matchQuery)
                .highlighter(highlightBuilder)
                .setFrom((pageNo - 1) * pageSize)
                .setSize(pageNo * pageSize)
                .get();
        // 返回搜索结果
        SearchHits hits = response.getHits();

        Long totalCount = hits.getTotalHits();
        Page<Map<String, Object>> page = new Page<>(pageNo, pageSize, totalCount.intValue());
        page.setList(getHitList(hits));
        return page;
    }

    @Override
    public void deleteIndex(String indexName) {
        elasticsearchTemplate.deleteIndex(indexName);
    }

    /**
     * 构造查询条件
     * @param keyword
     * @param fieldNames
     * @return
     */
    private QueryBuilder createQueryBuilder(String keyword, String... fieldNames) {
        // 构造查询条件，使用标准分词器
        return QueryBuilders.multiMatchQuery(keyword, fieldNames)
                .analyzer("ik_max_word")
                .operator(Operator.OR);
    }

    /**
     * 构造高亮器
     * @param fieldNames
     * @return
     */
    private HighlightBuilder createHighightBuilder(String... fieldNames) {
        // 设置高亮，使用默认高亮器
        HighlightBuilder highlightBuilder = new HighlightBuilder()
                .preTags("<span style='color:red'>")
                .postTags("</span>");
        // 设置高亮字段
        for (String field : fieldNames) {
            highlightBuilder.field(field);
        }
        return highlightBuilder;
    }

    /**
     * 处理高亮结果
     * @param hits
     * @return
     */
    private List<Map<String, Object>> getHitList(SearchHits hits) {
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map;
        for (SearchHit searchHit : hits) {
            map = new HashMap<>();
            // 处理源数据
            map.put("source", searchHit.getSourceAsMap());
            // 处理高亮数据
            Map<String, Object> hitMap = new HashMap<>();
            searchHit.getHighlightFields().forEach((k, v) -> {
                String hight = "";
                for (Text text : v.getFragments()) {
                    hight += text.string();
                }
                hitMap.put("highlight", hitMap);
            });
            map.put("highlight", hitMap);
            list.add(map);
        }
        return list;
    }
}
